class StockHeldJob
  include Sidekiq::Worker
  sidekiq_options :queue => :stock_held, :retry => false
  # 持仓股 job
  def perform(alert_message)
    logger.info alert_message
    Stock.where(is_held: true).each do |stock|
      logger.info "#{stock.symbol} -- #{stock.name}"
      if trade_time
        next if !Time.current.between?(Time.current.change(hour: 9, min: 30), Time.current.change(hour: 9, min: 45)) && Time.now.min % 3 != 0
        today = JSON.parse $Redis.get(stock["symbol"])
        ths_flow = RealTime.hs_ths_flow stock.symbol # 交易日每3分钟执行一次
        today["today_volume"] = today_volume stock.symbol # 量能
        today["ths_flow"] = ths_flow["title"]["je"]
        today["score"] = ths_flow["score"]
        today["buy_change"] = cul_change(stock.buy_price, today["trade"])
        today["sell_change"] = cul_change(stock.sell_price, today["trade"])

        stock.update(ths_flow: today["ths_flow"], score: today["score"], volume_change: today["today_volume"])

        content = <<~MD
          ** stock_held_job ***
          > #{stock.symbol} -- #{stock.name}
          > 涨幅: #{today["changepercent"]}%  
          > 资流: #{today["ths_flow"].to_f > 0 ? "↑" : "↓"} #{today["ths_flow"]}
          > 板块：#{stock.choice_block_tag}
          > 同量: #{today["today_volume"].to_f > 1 ? "↑" : "↓"} #{today["today_volume"]}  
          > 综评: #{today["score"]}  
          > [编辑](https://wyyzrx.com/admin/stocks/#{stock.id}/edit)
        MD

        Time.now.day > 15 ? (Robot.dd_held_ai content) : (Robot.dd_held content)
        # Robot.send_held content
        AlertRule.enabled.each do |rule|
          AlertService.check_rule(today, rule)
        end
      else
        logger.info "非交易时间"
      end
    end
  end
end




def today_volume(code)
  today = "#{trade_date(1)[0, 4]}-#{trade_date(1)[4, 2]}-#{trade_date(1)[6, 2]}"
  yesterday = "#{trade_date(2)[0, 4]}-#{trade_date(2)[4, 2]}-#{trade_date(2)[6, 2]}"

  kline = RealTime.hs_kline to_sina_code(code)
  today_5min = kline.select { |x| x["day"].split(" ")[0] == today }
  yesterday_5min = kline.select { |x| x["day"].split(" ")[0] == yesterday }.first(today_5min.count)

  today_volume = today_5min.pluck("volume").sum { |x| x.to_f }
  yes_volume = yesterday_5min.pluck("volume").sum { |x| x.to_f }
  (today_volume / yes_volume).round(2) if yes_volume != 0
end

def to_sina_code(code)
  return %w(5 6 9).include?(code.to_s[0]) ? "sh#{code}" : "sz#{code}" if code.size == 6
  code[-2..-1].downcase + code[0..5] if code[6] == "."
end

def trade_date(x)
  days = x < 10 ? x + 20 : x * 2.3
  sse = $TusharePro.tushare_pro("trade_cal", "exchange": "SSE", "start_date": (Time.now - days.day).strftime("%Y%m%d"), "end_date": (Time.now).strftime("%Y%m%d")).select { |sse| sse["is_open"] == 1 }
  sse[x - 1]["cal_date"]
end

def trade_time
  Time.current.between?(Time.current.change(hour: 9, min: 30), Time.current.change(hour: 11, min: 31)) || Time.current.between?(Time.current.change(hour: 13, min: 00), Time.current.change(hour: 15, min: 01))
end

def cul_change(open, close)
  ((close.to_f - open.to_f) * 100 / open.to_f).round(2)
end